package org.lc.stk.web.controller.course;

import java.util.List;

import org.lc.stk.model.course.KnowledgePoint;
import org.lc.stk.service.course.KnowledgePointService;
import org.lc.stk.web.response.ApiResponse;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@Tag(name = "知识点管理", description = "知识点的增删改查接口")
@SecurityRequirement(name = "bearerAuth")
public class KnowledgePointController {

    private final KnowledgePointService knowledgePointService;

    public KnowledgePointController(KnowledgePointService knowledgePointService) {
        this.knowledgePointService = knowledgePointService;
    }

    @PostMapping("/api/chapters/{chapterId}/knowledge-points")
    @Operation(summary = "创建知识点")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public ResponseEntity<ApiResponse<KnowledgePoint>> createKnowledgePoint(
            @Parameter(description = "课程ID") @RequestParam Integer courseId,
            @Parameter(description = "章节ID") @PathVariable Integer chapterId,
            @Parameter(description = "前置知识点ID列表") @RequestParam(required = false) List<Integer> preKnowledgeIds,
            @RequestBody KnowledgePoint knowledgePoint) {
        KnowledgePoint created = knowledgePointService.createKnowledgePoint(courseId, chapterId, 
                knowledgePoint, preKnowledgeIds);
        return ResponseEntity.ok(ApiResponse.success(created));
    }

    @PutMapping("/api/knowledge-points/{id}")
    @Operation(summary = "更新知识点")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public ResponseEntity<ApiResponse<KnowledgePoint>> updateKnowledgePoint(
            @Parameter(description = "知识点ID") @PathVariable Integer id,
            @Parameter(description = "前置知识点ID列表") @RequestParam(required = false) List<Integer> preKnowledgeIds,
            @RequestBody KnowledgePoint knowledgePoint) {
        KnowledgePoint updated = knowledgePointService.updateKnowledgePoint(id, knowledgePoint, preKnowledgeIds);
        return ResponseEntity.ok(ApiResponse.success(updated));
    }

    @DeleteMapping("/api/knowledge-points/{id}")
    @Operation(summary = "删除知识点")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteKnowledgePoint(
            @Parameter(description = "知识点ID") @PathVariable Integer id) {
        knowledgePointService.deleteKnowledgePoint(id);
        return ResponseEntity.ok(ApiResponse.success());
    }

    @GetMapping("/api/knowledge-points/{id}")
    @Operation(summary = "获取知识点详情")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<KnowledgePoint>> getKnowledgePoint(
            @Parameter(description = "知识点ID") @PathVariable Integer id) {
        return knowledgePointService.getKnowledgePointById(id)
                .map(point -> ResponseEntity.ok(ApiResponse.success(point)))
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/api/courses/{courseId}/knowledge-points")
    @Operation(summary = "获取课程的所有知识点")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<List<KnowledgePoint>>> getKnowledgePointsByCourse(
            @Parameter(description = "课程ID") @PathVariable Integer courseId) {
        List<KnowledgePoint> points = knowledgePointService.getKnowledgePointsByCourse(courseId);
        return ResponseEntity.ok(ApiResponse.success(points));
    }

    @GetMapping("/api/chapters/{chapterId}/knowledge-points")
    @Operation(summary = "获取章节的所有知识点")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<List<KnowledgePoint>>> getKnowledgePointsByChapter(
            @Parameter(description = "章节ID") @PathVariable Integer chapterId) {
        List<KnowledgePoint> points = knowledgePointService.getKnowledgePointsByChapter(chapterId);
        return ResponseEntity.ok(ApiResponse.success(points));
    }

    @GetMapping("/api/courses/{courseId}/knowledge-points/search")
    @Operation(summary = "搜索知识点")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<Page<KnowledgePoint>>> searchKnowledgePoints(
            @Parameter(description = "课程ID") @PathVariable Integer courseId,
            @Parameter(description = "知识点名称") @RequestParam String name,
            @PageableDefault(sort = {"id"}) Pageable pageable) {
        Page<KnowledgePoint> points = knowledgePointService.searchKnowledgePoints(courseId, name, pageable);
        return ResponseEntity.ok(ApiResponse.success(points));
    }

    @GetMapping("/api/knowledge-points/{id}/pre-knowledge")
    @Operation(summary = "获取前置知识点")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<List<KnowledgePoint>>> getPreKnowledgePoints(
            @Parameter(description = "知识点ID") @PathVariable Integer id) {
        List<KnowledgePoint> points = knowledgePointService.getPreKnowledgePoints(id);
        return ResponseEntity.ok(ApiResponse.success(points));
    }

    @GetMapping("/api/knowledge-points/{id}/next-knowledge")
    @Operation(summary = "获取后置知识点")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<List<KnowledgePoint>>> getNextKnowledgePoints(
            @Parameter(description = "知识点ID") @PathVariable Integer id) {
        List<KnowledgePoint> points = knowledgePointService.getNextKnowledgePoints(id);
        return ResponseEntity.ok(ApiResponse.success(points));
    }

    @PutMapping("/api/knowledge-points/{id}/move")
    @Operation(summary = "移动知识点到其他章节")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public ResponseEntity<ApiResponse<KnowledgePoint>> moveKnowledgePoint(
            @Parameter(description = "知识点ID") @PathVariable Integer id,
            @Parameter(description = "目标章节ID") @RequestParam Integer targetChapterId) {
        KnowledgePoint moved = knowledgePointService.moveKnowledgePoint(id, targetChapterId);
        return ResponseEntity.ok(ApiResponse.success(moved));
    }

    @GetMapping("/api/knowledge-points/{id}/can-delete")
    @Operation(summary = "检查知识点是否可以删除")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public ResponseEntity<ApiResponse<Boolean>> canDeleteKnowledgePoint(
            @Parameter(description = "知识点ID") @PathVariable Integer id) {
        boolean canDelete = knowledgePointService.canDelete(id);
        return ResponseEntity.ok(ApiResponse.success(canDelete));
    }

    @PostMapping("/api/knowledge-points/{id}/copy")
    @Operation(summary = "复制知识点到其他章节")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public ResponseEntity<ApiResponse<KnowledgePoint>> copyKnowledgePoint(
            @Parameter(description = "知识点ID") @PathVariable Integer id,
            @Parameter(description = "目标章节ID") @RequestParam Integer targetChapterId) {
        KnowledgePoint copied = knowledgePointService.copyKnowledgePoint(id, targetChapterId);
        return ResponseEntity.ok(ApiResponse.success(copied));
    }

    @GetMapping("/api/knowledge-points/check-circular-dependency")
    @Operation(summary = "检查知识点之间是否存在循环依赖")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public ResponseEntity<ApiResponse<Boolean>> checkCircularDependency(
            @Parameter(description = "当前知识点ID") @RequestParam Integer knowledgePointId,
            @Parameter(description = "要添加的前置知识点ID列表") @RequestParam List<Integer> preKnowledgeIds) {
        boolean hasCircular = knowledgePointService.hasCircularDependency(knowledgePointId, preKnowledgeIds);
        return ResponseEntity.ok(ApiResponse.success(hasCircular));
    }
}